// Park-data
var datakilde = null;
var statsTag = null; //  page tag to update stats on

/*
 * Parkdata
 * parkData[ix] array with parking-info. ix er P1, P2 etc.
 * parkData['P1'] contents:
 * 		parkData['P1'][0] = 'P1' (index)
 *  	parkData['P1'][1] = 25 (vacant)
 * 		parkData['P1'][1] = 50 (total)
 */
var parkData = new Array(); // Park-data array
/*
 * parkDataHist[ix] is an array with historical vacant parking for index 'ix'
 * parkDataHist['P1'] is also an array, so 
 * 		parkDataHist[ix][0] the park location name P1, P2 etc
 * 		parkDataHist[ix][1] how many entries are stored in this array
 * 		parkDataHist[ix][2..n] data entries - historic data. 
 */
var parkDataHist = new Array(); // Park history - array with number of vacant places
// Location should come from the server - here, hard-coded
var parkLocation = new Array(['P1',60.387239,5.333937,'Bygarasjen'],
		['P2',60.393116,5.316525,'Klostergarasjen'],
		['P3',60.393585,5.320107,'City Park'],
		['P4',60.388024,5.328498,'Grieg Park']);
// DataNames genererated on the server - here, hard-coded
var parkDataNames = new Array('P1','P2','P3','P4');

// Return the array of parking location names
function getParkPlasser() {
	return parkDataNames;
}

// Get the full parking name
function getParkFullName(theShortname) {
	for( i=0; i<parkLocation.length;i++) {
		var test = parkLocation[i];
		if(parkLocation[i][0] == theShortname) {
			return parkLocation[i][3];
		}
	}
}
// Return array with park lokations
function getParkLocation(whatLoc) {
	for( i=0; i<parkLocation.length;i++) {
		if(parkLocation[i][0] == whatLoc) {
			return parkLocation[i];
		}
	}
}

// Return the info-array for a location
function getParkInfo(pPlass) {
	for( j in parkData ) {
		if(j == pPlass ) {
			return parkData[j];
		}
	}
	return null;
}

//Return array with historical data for a location
function getParkHistorikk(pPlass) {
	for( i in parkDataHist) {
		var test = parkDataHist[i][0];
		if(parkDataHist[i][0]==pPlass) {
			return parkDataHist[i];
		}
	}
}

// Trim implementation
String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}

var datakilde = null; // EventSource

function startServerComm() {

 	// This works only in same domain...
    try {
        datakilde = new EventSource('http://stud.aitel.hist.no/~stud-svendah/html5/hent-status.php?t=30');
    } catch(err) {
        console.log(err.description);
    }
    if(datakilde==null) {
        return;
    }
	datakilde.onmessage = function(e) {
		parseData(e.data);
	};
	
	// hack for testdata locally
/*	parseData('P1,45,50;P2,7,10;P3,70,150;P4,244,250');
	parseData('P1,46,50;P2,8,10;P3,71,150;P4,245,250');
	parseData('P1,50,50;P2,10,10;P3,140,150;P4,200,250');
	parseData('P1,35,50;P2,10,10;P3,25,150;P4,75,250');
	parseData('P1,45,50;P2,5,10;P3,50,150;P4,200,250');
	
	// Testing - bruk av modell
	var plasser = getParkPlasser();
	var plass;
	for(plass = 0; plass < plasser.length; plass++) {
		console.log("Plass "+plasser[plass]);
		console.log("Informasjon:")
		var pInfo = getParkInfo(plasser[plass]);
		console.log("    Navn  :"+pInfo[0]+" - "+pInfo[3]);
		console.log("    Ledig :"+pInfo[1]);
		console.log("    Max   :"+pInfo[2]);
		
		var theLoc = getParkLocation(pInfo[0]);
		console.log("    Hvor  :"+theLoc[1]+", "+theLoc[2]);
		
		var theHist = getParkHistorikk(pInfo[0]);
		var histString = "";
		for( j = 2;j<theHist.length;j++ ) {
			histString += " "+theHist[j];
		}
		console.log("    Historikk  :"+theHist[1]+" entries: "+histString);
	}
	*/
}		

function consoleDump() {
    return; // only when debugging
	console.log("------ PARKDATA ------");
	for(j in parkData) {
		console.log("! " + parkData[j]);
	}
	console.log("------ Historikk ------");
	for(j in parkDataHist) {
		console.log("! " + parkDataHist[j]);
	}
	console.log("-----------------------");
}

// Parse data from the server
function parseData(data) {
	// P1,45,50;P2,7,10;P3,70,150;P4,244,250
	var mySplitResult = data.trim().split(";");
	var splitData = null;
	var i;
	var j;
	for(i=0;i<mySplitResult.length;i++) {
		//console.log(" "+i+" : "+mySplitResult[i]);
		splitData = mySplitResult[i].split(",");

		// Park-data (assosiative array)
		var foundIndex = null;
		for(j in parkData) {
			if(splitData[0] == parkData[j][0]) {
				//console.log("Fant index " + j);
				foundIndex = j;
				break;
			}
		}
		var test;
		if(foundIndex==null) {
			//console.log("Ny plass " + splitData[0]);
			parkData[splitData[0]] = new Array();
			test = parkData[splitData[0]]; // always initiated...
		} else {
			//console.log("Oppd index " + foundIndex);
			test = parkData[foundIndex];
		}
		test[0] = splitData[0];
		test[1] = splitData[1];
		test[2] = splitData[2];
		
		// History
		for(j in parkDataHist) {
			if(splitData[0] == parkDataHist[j][0]) {
				//console.log("Fant den");
				foundIndex = j;
				break;
			}
		}		
		if(foundIndex==null) {
			parkDataHist[splitData[0]] = new Array();
			test = parkDataHist[splitData[0]]; // always initiated...
			test[0] = splitData[0];
			test[1] = 0;
		} else {
			test = parkDataHist[foundIndex];
		}
		// Save the last free oisition, index 0=name, index 1=number of entries after index 1
		test[2+test[1]++] = splitData[1]; 
	}
	// For debugging
	//consoleDump();
	
	// Update stats - if tag is set
	updateParkStats();
	visParkStat();
	updateIcons(data);
}

//Function to set the tag for updates from the server
function setParkIdUpdate(theIdTag) {
	statsTag = theIdTag;
	if (statsTag != null) {
		updateParkStats();
	}
}

// Actually reading the code is a bit different than lookin on it...

// Update the park stats - front page 
function updateParkStats() {
	if(statsTag==null) {
		return;
	}
	var docElm = document.getElementById(statsTag);
	if(docElm != null) {
		var newHtml = "";
		newHtml = "";
		
		var plasser = getParkPlasser();
		var plass;
		for(plass = 0; plass < plasser.length; plass++) {
			var pInfo = getParkInfo(plasser[plass]);
			if(pInfo != null) {
				newHtml += (""+pInfo[0] + ": " + pInfo[1] + "/" + pInfo[2] + " ");
				if(plass==1) {
					newHtml += "<br/>";
				}
			}
		}
		docElm.innerHTML = newHtml;
	}
}
